package com.lp.controller.iot;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lp.bo.IotSensorInfoBO;
import com.lp.bo.IotTriggerInfoBO;
import com.lp.bo.UserInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.common.Code;
import com.lp.common.Constants;
import com.lp.common.RequestURLIOT;
import com.lp.controller.BaseController;
import com.lp.util.ObjectUtil;
import com.lp.util.ResultMapUtils;


@Controller
public class IotTriggerInfoController extends BaseController {

	/**
	 * 检索
	 * @param response
	 * @param 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.TriggerInfo.TRIGGER_INFO_PAGE)
	public ModelAndView selectPage(HttpServletResponse response, 
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
			@RequestBody IotTriggerInfoBO obj,
			@RequestParam(required=false) Integer pageSize ,
			@RequestParam Integer paged ) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO user = getUserInfoByUserKey(userKey);
			obj.setUser_id(user.getId());
			if( ObjectUtil.isNotEmpty(obj.getFrom_sensor_id()) || ObjectUtil.isNotEmpty(obj.getScene_id()) || ObjectUtil.isNotEmpty(obj.getNode_id())  ){
				resultMap = service.selectPageList("IotTriggerInfo.selectPage",getPageBean(paged,pageSize), obj);	
			}
		} catch (Exception e) {
			exception(e,resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}
	
	/**
	 * 插入
	 * @param response
	 * @param 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = RequestURLIOT.TriggerInfo.TRIGGER_INFO )
	public ModelAndView save(HttpServletResponse response, 
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
			@RequestBody IotTriggerInfoBO obj ) {
		Map<String, Object> resultMap = getResultMap();
		try {
			// 增加触发器状态
//			obj.setIot_trigger_status(CodeIot.IOT_TRIGGER_STATUS.NORMAL);
			// 设置添加用户信息
			UserInfoBO user = getUserInfoByUserKey(userKey);
			obj.setAid(user.getId());
			resultMap = service.insert("IotTriggerInfo.insert", obj) ;
			if(isOk(resultMap)){
				// 更新触发器缓存
				resultMap = service.selectList("IotSensorInfo.selectSensorTriggerList", new IotSensorInfoBO(obj.getFrom_sensor_id()));
				if(isOk(resultMap)){
					IotSensorInfoBO iotSensorObj = ((List<IotSensorInfoBO>) getData(resultMap)).get(0);
					ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, iotSensorObj.getNode_id()+"-"+ 
							iotSensorObj.getSensor_device_id()+"-"+iotSensorObj.getPort_id(), iotSensorObj);
					
					// 判断
					if(obj.getIot_trigger_condition_type() == 280){
						List<IotTriggerInfoBO> triggerList = ProCacheUtil.getCache(CacheName.NODETRIGGERINFO, obj.getNode_id()+"");
						if(ObjectUtil.isNotEmpty(triggerList)){
							triggerList.add(obj);
						}else{
							List<IotTriggerInfoBO> tmps = new ArrayList<IotTriggerInfoBO>();
							tmps.add(obj);
							ProCacheUtil.addCache(CacheName.NODETRIGGERINFO, obj.getNode_id()+"" , tmps );
						}
					}
				}
			}
		} catch (Exception e) {
			exception(e,resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}
	
	/**
	 * 查询单个
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = RequestURLIOT.TriggerInfo.TRIGGER_INFO)
	public ModelAndView selectOne(HttpServletResponse response, 
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
			@RequestParam Integer id ) {
		Map<String, Object> resultMap = getResultMap();
		try {
			resultMap = service.selectOne("IotTriggerInfo.selectOne", new IotTriggerInfoBO(id)) ;
		} catch (Exception e) {
			exception(e,resultMap, id);
		}
		return getModelAndView(response, resultMap);
	}
	
	/**
	 * 更新
	 * @param response
	 * @param obj
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, value = RequestURLIOT.TriggerInfo.TRIGGER_INFO)
	public ModelAndView update(HttpServletResponse response, 
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
			@RequestBody IotTriggerInfoBO obj ) {
		Map<String, Object> resultMap = getResultMap();
		try {
			Integer osensorId = null ;
			Integer onodeId = null ;
			// 判断是否有修改了传感器
			if( ObjectUtil.isNotEmpty(obj.getFrom_sensor_id())  ){
				// 这边传感器变了
				resultMap = service.selectOne("IotTriggerInfo.selectOne", new IotTriggerInfoBO(obj.getId()));
				IotTriggerInfoBO orginTrigger = (IotTriggerInfoBO) getData(resultMap) ;
				if(  orginTrigger.getFrom_sensor_id() != obj.getFrom_sensor_id()+0 ){
					osensorId =  orginTrigger.getFrom_sensor_id() ;
				}
			}
			UserInfoBO user = getUserInfoByUserKey(userKey);
			obj.setUser_id(user.getId());
			obj.setMid( user.getId() );
			resultMap = service.update("IotTriggerInfo.update", obj) ;
			if(isOk(resultMap)){
				// 首先把原来的传感器更新下
				if(ObjectUtil.isNotEmpty(osensorId)){
					// 更新触发器缓存
					resultMap = service.selectList("IotSensorInfo.selectSensorTriggerList", new IotSensorInfoBO(osensorId));
					IotSensorInfoBO iotSensorObj = null ; 
					if(isOk(resultMap)){
						iotSensorObj = ((List<IotSensorInfoBO>) getData(resultMap)).get(0);
						ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, iotSensorObj.getNode_id()+"-"+ 
								iotSensorObj.getSensor_device_id()+"-"+iotSensorObj.getPort_id(), iotSensorObj);
					}else{
						// 这边没有了
						iotSensorObj = ProCacheUtil.getCache(CacheName.SENSORINFO, osensorId +"");
						ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, iotSensorObj.getNode_id()+"-"+ 
								iotSensorObj.getSensor_device_id()+"-"+iotSensorObj.getPort_id(), iotSensorObj);
						
					}
					if(ObjectUtil.isNotEmpty(obj.getNode_id()) && obj.getNode_id() !=  iotSensorObj.getNode_id()+0){
						onodeId = iotSensorObj.getNode_id() ;
					}
				}
				
				// 检索最新更新传感器
				resultMap = service.selectOne("IotTriggerInfo.selectOne", new IotTriggerInfoBO(obj.getId()));
				obj = (IotTriggerInfoBO) getData(resultMap) ;
				
				// 更新触发器缓存
				resultMap = service.selectList("IotSensorInfo.selectSensorTriggerList", new IotSensorInfoBO(obj.getFrom_sensor_id()));
				if(isOk(resultMap)){
					IotSensorInfoBO iotSensorObj = ((List<IotSensorInfoBO>) getData(resultMap)).get(0);
					ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, iotSensorObj.getNode_id()+"-"+ 
							iotSensorObj.getSensor_device_id()+"-"+iotSensorObj.getPort_id(), iotSensorObj);
				}
				
				// 网关离线的触发器更新
				IotTriggerInfoBO triggerInfo = new IotTriggerInfoBO();
				triggerInfo.setIot_trigger_condition_type(280);
				triggerInfo.setNode_id(obj.getNode_id());
				resultMap = service.selectList("IotTriggerInfo.select", triggerInfo) ;
				List<IotTriggerInfoBO> iotTriggerInfoBOList  = getData(resultMap) ;
				if( ObjectUtil.isNotEmpty( iotTriggerInfoBOList ) ){
					ProCacheUtil.addCache(CacheName.NODETRIGGERINFO, obj.getNode_id().toString() , iotTriggerInfoBOList);
				}else{
					ProCacheUtil.removeCache(CacheName.NODETRIGGERINFO, obj.getNode_id().toString());
					putStatusCode(resultMap, Code.ResponseCode.SystemCode.OK);
				}
				
				if(onodeId != null ){
					// 网关离线的触发器更新
					triggerInfo = new IotTriggerInfoBO();
					triggerInfo.setIot_trigger_condition_type(280);
					triggerInfo.setNode_id(onodeId);
					resultMap = service.selectList("IotTriggerInfo.select", triggerInfo) ;
					iotTriggerInfoBOList  = getData(resultMap) ;
					if( ObjectUtil.isNotEmpty( iotTriggerInfoBOList ) ){
						ProCacheUtil.addCache(CacheName.NODETRIGGERINFO, onodeId.toString() , iotTriggerInfoBOList);
					}else{
						ProCacheUtil.removeCache(CacheName.NODETRIGGERINFO, onodeId.toString());
						putStatusCode(resultMap, Code.ResponseCode.SystemCode.OK);
					}
				}
				
//				ProCacheUtil.removeCache(CacheName.NODETRIGGERINFO, obj.getNode_id().toString());
//				if( ObjectUtil.isNotEmpty(iotTriggerInfoBOList) ){
//					for(IotTriggerInfoBO tmp: iotTriggerInfoBOList){
//						List<IotTriggerInfoBO> objs = ProCacheUtil.getCache(CacheName.NODETRIGGERINFO, tmp.getNode_id().toString()) ;
//						if( ObjectUtil.isNotEmpty( objs ) ){
//							objs.add(tmp);
//						}else{
//							objs = new ArrayList<>();
//							objs.add(tmp);
//							ProCacheUtil.addCache(CacheName.NODETRIGGERINFO, tmp.getNode_id().toString() , objs);
//						}
//					}
//				}else{
//					putStatusCode(resultMap, Code.ResponseCode.SystemCode.OK);
//				}
			}
		} catch (Exception e) {
			exception(e,resultMap, obj);
		}
		return getModelAndView(response, resultMap);
	}
	
	/**
	 * 删除
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(method = RequestMethod.DELETE, value = RequestURLIOT.TriggerInfo.TRIGGER_INFO)
	public ModelAndView delete(HttpServletResponse response, 
			@RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
			@RequestParam Integer id ) {
		Map<String, Object> resultMap = getResultMap();
		try {
			IotTriggerInfoBO obj = new IotTriggerInfoBO();
			if(ObjectUtil.isEmpty(id)){
				putStatusCode(resultMap, Code.ResponseCode.SystemCode.PARAM_ERROR);
			}else{
				UserInfoBO user = getUserInfoByUserKey(userKey);
				obj.setUser_id(user.getId());
				obj.setId(id);
				obj.setDelete_flag(Constants.DELETE.YES);
				obj.setMid( user.getId() );
				resultMap = service.update("IotTriggerInfo.update", obj) ;	
				// 更新传感器触发器缓存
				if(isOk(resultMap)){
					resultMap = service.selectOne("IotTriggerInfo.selectOne", new IotTriggerInfoBO(id));
					obj = (IotTriggerInfoBO) getData(resultMap) ;
					// 更新触发器缓存
					resultMap = service.selectList("IotSensorInfo.selectSensorTriggerList", new IotSensorInfoBO(obj.getFrom_sensor_id()));
					if(isOk(resultMap)){
						IotSensorInfoBO iotSensorObj = ((List<IotSensorInfoBO>) getData(resultMap)).get(0);
						ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, iotSensorObj.getNode_id()+"-"+ 
								iotSensorObj.getSensor_device_id()+"-"+iotSensorObj.getPort_id(), iotSensorObj);
					}else{
						// 如果没有了，则需要
						IotSensorInfoBO iotSensorObj = ProCacheUtil.getCache(CacheName.SENSORINFO, obj.getFrom_sensor_id()+"");

						ProCacheUtil.addCache(CacheName.SENSORTRIGGERINFO, iotSensorObj.getNode_id()+"-"+ 
								iotSensorObj.getSensor_device_id()+"-"+iotSensorObj.getPort_id(), iotSensorObj);
					}
					
					// 更新这个设备node的触发器
					IotTriggerInfoBO triggerInfo = new IotTriggerInfoBO();
					triggerInfo.setIot_trigger_condition_type(280);
					triggerInfo.setNode_id(obj.getNode_id());
					resultMap = service.selectList("IotTriggerInfo.select", triggerInfo) ;
					List<IotTriggerInfoBO> iotTriggerInfoBOList  = getData(resultMap) ;
					ProCacheUtil.removeCache(CacheName.NODETRIGGERINFO, obj.getNode_id().toString());
					if( ObjectUtil.isNotEmpty( iotTriggerInfoBOList ) ){
						ProCacheUtil.addCache(CacheName.NODETRIGGERINFO, obj.getNode_id().toString() , iotTriggerInfoBOList);
					}else{
						ProCacheUtil.removeCache(CacheName.NODETRIGGERINFO, obj.getNode_id().toString());
						putStatusCode(resultMap, Code.ResponseCode.SystemCode.OK);
					}
					
//					if( ObjectUtil.isNotEmpty(iotTriggerInfoBOList) ){
//						for(IotTriggerInfoBO tmp: iotTriggerInfoBOList){
//							List<IotTriggerInfoBO> objs = ProCacheUtil.getCache(CacheName.NODETRIGGERINFO, tmp.getNode_id().toString()) ;
//							if( ObjectUtil.isNotEmpty( objs ) ){
//								objs.add(tmp);
//							}else{
//								objs = new ArrayList<>();
//								objs.add(tmp);
//								ProCacheUtil.addCache(CacheName.NODETRIGGERINFO, tmp.getNode_id().toString() , objs);
//							}
//						}
//					}else{
//						putStatusCode(resultMap, Code.ResponseCode.SystemCode.OK);
//					}
				}
			}
		} catch (Exception e) {
			exception(e,resultMap, id);
		}
		return getModelAndView(response, resultMap);
	}
}
